<script lang='ts' setup>
import { computed, reactive } from 'vue'
import { resources_make_dir } from '@/apis/toolbox/resources/resources_make_dir.ts'

const emits = defineEmits(['update:show', 'success'])

const props = defineProps({
  show: { required: true, type: Boolean },
  path: { required: true, type: String }
})

const state = reactive<{ start: number, path: string, saving: boolean }>({ start: 1, path: '', saving: false })

const current = computed((): string => {
  const strings = props.path!.slice(0, props.path!.length - 1).split('/')
  if (3 >= strings.length) {
    return props.path!
  }

  return '.../' + strings.slice(strings.length - 3).join('/') + '/'
})

async function close(): Promise<void> {
  state.start = 1
  state.path = ''
  emits('update:show', false)
}

async function make(): Promise<void> {
  state.saving = true
  const response = await resources_make_dir(1 === state.start ? state.path : props.path + state.path)
  state.saving = false

  if (0 !== response.code) {
    window.$message.error(response.message)

    return
  }

  window.$message.success('创建完成')
  await close()
  emits('success')
}
</script>

<template>
  <n-modal :show='props.show' class='resources-make-dir-modal' transform-origin='center' @update:show='close'>
    <n-card>
      <n-space vertical>
        <n-divider>创建目录</n-divider>
        <div>
          <n-space :wrap-item='false' align='center'>
            <div>起始位置</div>
            <div>
              <n-radio-group v-model:value='state.start' size='small'>
                <n-radio :value='1' size='small'>根目录</n-radio>
                <n-radio :value='2' size='small'>当前目录</n-radio>
              </n-radio-group>
            </div>
            <div class='flex-max'>
              <n-input-group>
                <n-input-group-label size='small'>{{ 1 === state.start ? '/' : current }}</n-input-group-label>
                <n-input v-model:value='state.path' placeholder='创建的目录，支持多级目录，使用/分割' size='small' />
              </n-input-group>
            </div>
          </n-space>
        </div>
        <div>
          <n-space align='center' justify='center'>
            <n-button size='small' type='error' @click='close'>取消</n-button>
            <n-button :loading='state.saving' size='small' type='primary' @click='make'>创建</n-button>
          </n-space>
        </div>
      </n-space>
    </n-card>
  </n-modal>
</template>

<style scoped>
.resources-make-dir-modal {
  width: 800px;
}
</style>
